<script setup lang="ts">
import { ref, reactive, nextTick, toRef, toRefs } from 'vue'
import { getIngredientsList, addIngredientsList, updateIngredients, deleteIngredient } from '@/api/ingredients';
import type { Page } from '@/api/types/page';
import type { Ingredients, IngredientsSearchParam } from '@/api/ingredients/types';
import { ElMessage, ElMessageBox, rowProps, type FormInstance, type FormRules, type UploadFile, type UploadProps, type UploadUserFile } from 'element-plus';
import { useDict } from '@/util/usedict'
import { fi } from 'element-plus/es/locales.mjs';

const INGREDIENTS = 'ingredients'
const { dict, showDictName } = useDict(INGREDIENTS)
/* 图片的虚拟路径 */
const base_url = import.meta.env.VITE_APP_BASE_API

const queryFormRef = ref<FormInstance>()
const queryForm = reactive<IngredientsSearchParam>({
    pageNum: 1,
    pageSize: 1,
    name: '',
    type: ''
})
// let {name,type} = toRefs(queryForm)
/* 食材列表 */
const total = ref(0)
const ingredientsList = ref<Ingredients[]>([])

const listIngredients = (pageNumber = 1) => {
    queryForm.pageNum = pageNumber

    getIngredientsList(queryForm)
        .then((page: Page<Ingredients>) => {
            total.value = page.total
            ingredientsList.value = page.rows
        }).catch(e => {
            console.log(e)
        })
}
listIngredients()

/* 重置 */
const resetQueryForm = () => {
    queryFormRef.value?.resetFields()
    listIngredients()
}

/* 添加和修改form */
const imageLimit = ref(1)

const ingredientFormTitle = ref('添加操作')

const ingredientFormVisible = ref(false)

const ingredientFormRef = ref<FormInstance>()
const ingredientFormRules = ref<FormRules>({
    name: [{ required: true, message: '请填写菜品名称' }],
    type: [{ required: true, message: '请选择菜品类型' }],
    url: [{ required: true, message: '请填写菜品图片' }],
    description: [{ required: true, message: '请填写菜品描述' }]
})
const ingredientForm = ref<Ingredients>({
    name: '',
    type: '',
    url: '',
    description: ''
})

const handleAdd = () => {
    ingredientFormVisible.value = true
    nextTick(() => {
        ingredientFormTitle.value = '添加操作'
        fileList.value = []

        ingredientFormRef.value?.resetFields()
        ingredientForm.value = {
            name: '',
            type: '',
            url: '',
            description: ''
        }
    })


}

const handleEdit = (row: Ingredients) => {
    // 图片赋值
    fileList.value = [
        {
            name: row.url,
            url: base_url + row.url
        }]
    ingredientFormTitle.value = '编辑操作'
    ingredientForm.value = { ...row }
    nextTick(() => {
        ingredientFormRef.value?.validateField('url')
    })
    // ingredientFormRef.value?.resetFields()
    ingredientFormVisible.value = true
}
/* 添加 */
const confirm = () => {

    ingredientFormRef.value?.validate(async valid => {
        if (valid) {
            if (!ingredientForm.value.id) {
                await addIngredientsList(ingredientForm.value)
                ElMessage.success('操作成功')

                queryForm.pageNum = 1
            } else {
                // 修改
                await updateIngredients(ingredientForm.value.id, ingredientForm.value)
                ElMessage.success('操作成功')
            }


            ingredientFormVisible.value = false

            listIngredients(queryForm.pageNum)


        }
    })
}


/* 刪除 */
const delIngredient = async (id: number) => {

    await deleteIngredient(id)
    listIngredients()
}


/* 图片操作 */
const fileList = ref<UploadUserFile[]>()

const onHandlerExceed: UploadProps['onExceed'] = () => {
    ElMessage.error("不能传入超过一张图片!")
}

const handleRemove: UploadProps['onRemove'] = (file: UploadFile) => {
    ingredientForm.value.url = ''
    ingredientFormRef.value?.validateField('url')
}

const handleSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
    ingredientForm.value.url = response.data
    ingredientFormRef.value?.validateField('url')
}

const handleUpload: UploadProps['beforeUpload'] = (file: File) => {

    const ifImage = file.type == 'image/jpeg'
    const ifPng = file.type == 'image/png'

    console.log(file.type)
    const ifToBig = file.size / 1024 / 1024 < 1

    if (ifImage || ifPng) {
        if (!ifToBig) {
            ElMessage.error("请传入小于1MB大小的文件")
            return false;
        }
    } else {
        ElMessage.error("请输入JPG PNG格式文件")
        return false;
    }
} 
</script>

<template>
    <div class="app-container">
        <el-form :model="queryForm" ref="queryFormRef" inline>
            <el-form-item label="食材名称" prop="name">
                <el-input v-model="queryForm.name" placeholder="请输入食材名称"></el-input>
            </el-form-item>
            <!-- 食材类型 -->
            <el-form-item label="食材类型" prop="type">
                <el-select style="width:180px" v-model="queryForm.type" placeholder="请选择" clearable>
                    <el-option v-for="item in dict[INGREDIENTS]" :key="item.value" :label="item.name"
                        :value="item.value"></el-option>
                </el-select>
            </el-form-item>
            <!-- 按钮 -->
            <el-form-item>
                <el-button icon="Search" type="primary" @click="listIngredients()">搜索</el-button>
                <el-button icon="Refresh" plain type="info" @click="resetQueryForm">重置</el-button>
                <el-button icon="Plus" plain type="success" @click="handleAdd">添加</el-button>
            </el-form-item>
        </el-form>

        <!-- 列表 -->
        <el-table :data="ingredientsList" border stripe style="width:100%">
            <el-table-column type="index" label="编号" width="80px" align="center"></el-table-column>
            <el-table-column label="食材名称" prop="name" align="center"></el-table-column>
            <el-table-column label="食材类型" align="center">
                <template #default="{ row }">
                    <el-tag type="success">{{ showDictName(INGREDIENTS, row.type) }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="食材图片">
                <template #default="{ row }">
                    <el-image align="center" :src="base_url + row.url" style="width:40px;height:40px"
                        :preview-src-list="[base_url + row.url]" preview-teleported />
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="200">
                <template #default="scope">
                    <el-button icon="Edit" plain type="primary" @click="handleEdit(scope.row)">修改</el-button>
                    <el-button icon="Delete" plain type="danger" @click="delIngredient(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination style="margin-top: 10px" :total="total" layout="total,sizes,prev,pager,next,jumper" background
            :page-sizes="[1, 5, 10, 50]" v-model:current-page="queryForm.pageNum" v-model:page-size="queryForm.pageSize"
            @current-change="listIngredients" @size-change="listIngredients()"></el-pagination>
    </div>

    <el-dialog :title="ingredientFormTitle" width="600px" v-model="ingredientFormVisible" :close-on-click-modal="false">
        <el-form ref="ingredientFormRef" :model="ingredientForm" :rules="ingredientFormRules">
            <el-form-item label="食材名称" prop="name">
                <el-input placeholder="请填写食材名称" v-model="ingredientForm.name"></el-input>
            </el-form-item>
            <el-form-item label="食材图片" prop="url">
                <el-upload v-model:file-list="fileList" class="upload-demo"
                    :action="base_url + '/dishes-service/upload/image'" :on-remove="handleRemove"
                    :on-success="handleSuccess" :before-upload="handleUpload" :on-exceed="onHandlerExceed"
                    :limit="imageLimit" list-type="picture">
                    <el-button type="primary">上传图片</el-button>
                    <template #tip>
                        <div class="el-upload__tip">
                            格式仅限jpg/png 大小限制1mb以内
                        </div>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item label="食材类型" prop="type">
                <el-radio-group v-model="ingredientForm.type">
                    <el-radio v-for="item in dict[INGREDIENTS]" :label="item.name" :value="item.value" />
                </el-radio-group>
            </el-form-item>
            <el-form-item label="食材描述" prop="description">
                <el-input type="trextarea" placeholder="请输入食材描述" v-model="ingredientForm.description"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
                <div class="dialog-footer">
                    <el-button @click="ingredientFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirm">
                        确认
                    </el-button>
                </div>
            </template>

    </el-dialog>
</template>

<style scoped>
:deep(.el-upload-list__item) {
    transition: none !important;
}
</style>